<template>
  <div class="patient-management">
    <!-- 顶部导航栏 -->
    <van-nav-bar
      title="就诊人管理"
      fixed
      placeholder
      safe-area-inset-top
      :border="false"
      :style="{ backgroundColor: '#1989fa', color: 'white', zIndex: 101 }"
      left-arrow
      @click-left="handleGoBack"
    />

    <!-- 患者卡片列表区域 -->
    <div class="patient-cards-container">
      <div v-if="patients.length === 0" class="empty-tip">
        暂无就诊人，请点击下方「添加就诊人」按钮创建
      </div>

      <!-- 左滑删除功能 -->
      <van-swipe-cell
        v-else
        v-for="patient in patients"
        :key="patient.patient_id"
        class="patient-swipe-cell"
        :stop-propagation="true"
        @open="handleSwipeOpen(patient.patient_id)"
        @close="handleSwipeClose"
      >
        <!-- 卡片内容 -->
        <div
          class="patient-card"
          :class="{ 'active-patient': activePatientId === patient.patient_id }"
          @click="setActivePatient(patient.patient_id)"
        >
          <div class="patient-header">
            <!-- 默认就诊人标识（五角星） -->
            <van-icon
              name="star"
              :color="defaultPatientId === patient.patient_id ? '#e6e600' : '#ccc'"
              :class="{ 'filled-star': defaultPatientId === patient.patient_id }"
              class="default-star"
              @click.stop="toggleDefaultPatient(patient.patient_id)"
            />

            <div class="patient-info">
              <div class="name-and-tag">
                <span class="patient-name">{{ patient.name }}</span>
                <van-tag type="primary" size="medium" class="relation-tag">
                  {{ patient.relationship }}
                </van-tag>
              </div>

              <div class="patient-details">
                <div class="detail-item">
                  <van-icon name="user-o" size="14px" />
                  <span>{{ genderMap[patient.gender] }} | {{ getAge(patient.birth_date) }}岁</span>
                </div>
                <div class="detail-item">
                  <van-icon name="phone" size="14px" />
                  <span>{{ patient.phone }}</span>
                </div>
                <div v-if="patient.id_card" class="detail-item">
                  <van-icon name="id-card" size="14px" />
                  <span>{{ maskIdCard(patient.id_card) }}</span>
                </div>
              </div>
            </div>
          </div>

          <!-- 编辑按钮 -->
          <div class="card-footer">
            <van-button
              icon="edit"
              type="primary"
              size="small"
              plain
              class="edit-btn"
              @click.stop="editPatient(patient.patient_id)"
            >
              编辑
            </van-button>
          </div>
        </div>

        <!-- 左滑删除按钮 -->
        <template #right>
          <van-button
            square
            type="danger"
            class="delete-button"
            icon="delete"
            @click.stop="deletePatient(patient.patient_id)"
          >
            删除
          </van-button>
        </template>
      </van-swipe-cell>
    </div>

    <!-- 添加就诊人按钮（底部固定） -->
    <van-button
      class="add-patient-btn"
      type="primary"
      round
      icon="plus"
      @click="showAddPatientDialog"
    >
      添加就诊人
    </van-button>

    <!-- 弹窗：添加/编辑就诊人 -->
    <van-dialog
      v-model:show="showAddDialog"
      :title="isEditing ? '编辑就诊人' : '添加就诊人'"
      show-cancel-button
      @cancel="resetForm"
      :close-on-click-overlay="false"
      :z-index="2000"
    >
      <van-form ref="addForm" @submit="handleAddConfirm">
        <van-cell-group inset class="scrollable-form">
          <!-- 姓名（必填） -->
          <van-field
            v-model="newPatient.name"
            name="name"
            placeholder="请输入姓名"
            :rules="[{ required: true, message: '请填写姓名' }]"
            class="required-field"
          >
            <template #label>
              姓名<span class="required-asterisk">*</span>
            </template>
          </van-field>

          <!-- 性别（必填） -->
          <van-field
            v-model="newPatient.genderText"
            name="genderText"
            placeholder="请选择性别"
            is-link
            readonly
            @click="handleOpenGenderPicker"
            :rules="[{ required: true, message: '请选择性别' }]"
            class="required-field"
          >
            <template #label>
              性别<span class="required-asterisk">*</span>
            </template>
          </van-field>

          <!-- 出生日期（必填） -->
          <van-field
            v-model="newPatient.birthDate"
            name="birthDate"
            placeholder="请选择出生日期"
            is-link
            readonly
            @click="showDatePopup"
            :rules="[{ required: true, message: '请选择出生日期' }]"
            class="required-field"
          >
            <template #label>
              出生日期<span class="required-asterisk">*</span>
            </template>
          </van-field>

          <!-- 手机号（必填） -->
          <van-field
            v-model="newPatient.phone"
            name="phone"
            placeholder="请输入手机号"
            :rules="[{ required: true, message: '请填写手机号' }, { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号' }]"
            class="required-field"
          >
            <template #label>
              手机号<span class="required-asterisk">*</span>
            </template>
          </van-field>

          <!-- 身份证（必填） -->
          <van-field
            v-model="newPatient.idCard"
            name="idCard"
            placeholder="请输入18位身份证号"
            :rules="[{ required: true, message: '请填写身份证号' }, { pattern: /^\d{17}[\dXx]$/, message: '请输入18位有效身份证号' }]"
            class="required-field"
          >
            <template #label>
              身份证<span class="required-asterisk">*</span>
            </template>
          </van-field>

          <!-- 关系（必填） -->
          <van-field
            v-model="newPatient.relationText"
            name="relationText"
            placeholder="请选择关系"
            is-link
            readonly
            @click="handleOpenRelationPicker"
            :rules="[{ required: true, message: '请选择关系' }]"
            class="required-field"
          >
            <template #label>
              关系<span class="required-asterisk">*</span>
            </template>
          </van-field>

          <!-- 身高（选填） -->
          <van-field
            v-model="newPatient.height"
            name="height"
            label="身高(cm)"
            placeholder="请输入身高（选填）"
            type="number"
            class="optional-field"
          />

          <!-- 体重（选填） -->
          <van-field
            v-model="newPatient.weight"
            name="weight"
            label="体重(kg)"
            placeholder="请输入体重（选填）"
            type="number"
            class="optional-field"
          />

          <!-- 血型（必填） -->
          <van-field
            v-model="newPatient.bloodTypeText"
            name="bloodTypeText"
            placeholder="请选择血型"
            is-link
            readonly
            @click="handleOpenBloodTypePicker"
            :rules="[{ required: true, message: '请选择血型' }]"
            class="required-field"
          >
            <template #label>
              血型<span class="required-asterisk">*</span>
            </template>
          </van-field>
        </van-cell-group>
      </van-form>

      <!-- 弹窗底部按钮 -->
      <template #footer>
        <div class="dialog-footer-buttons">
          <van-button
            type="default"
            @click="resetForm"
            class="dialog-btn cancel-btn"
          >
            取消
          </van-button>
          <van-button
            type="primary"
            @click="submitForm"
            class="dialog-btn confirm-btn"
          >
            {{ isEditing ? '保存修改' : '添加就诊人' }}
          </van-button>
        </div>
      </template>
    </van-dialog>

    <!-- 性别选择器弹窗 -->
    <van-popup
      v-model:show="showGenderPicker"
      position="bottom"
      :z-index="2100"
      :overlay="true"
    >
      <van-picker
        title="选择性别"
        :columns="genderOptions"
        @confirm="onGenderConfirm"
        @cancel="showGenderPicker = false"
        :default-index="genderOptions.findIndex(item => item.value === newPatient.gender)"
      />
    </van-popup>

    <!-- 关系选择器弹窗 -->
    <van-popup
      v-model:show="showRelationPicker"
      position="bottom"
      :z-index="2100"
      :overlay="true"
    >
      <van-picker
        title="选择关系"
        :columns="relationOptions"
        @confirm="onRelationConfirm"
        @cancel="showRelationPicker = false"
        :default-index="relationOptions.findIndex(item => item.value === newPatient.relationship)"
      />
    </van-popup>

    <!-- 血型选择器弹窗 -->
    <van-popup
      v-model:show="showBloodTypePicker"
      position="bottom"
      :z-index="2100"
      :overlay="true"
    >
      <van-picker
        title="选择血型"
        :columns="bloodTypeOptions"
        @confirm="onBloodTypeConfirm"
        @cancel="showBloodTypePicker = false"
        :default-index="bloodTypeOptions.findIndex(item => item.value === newPatient.blood_type)"
      />
    </van-popup>

    <!-- 日期选择器弹窗 -->
    <van-popup v-model:show="datePickerShow" position="bottom" round>
      <van-picker
        :columns="dateColumns"
        v-model="currentDate"
        @change="onDateChange"
        @confirm="confirmDate"
        @cancel="cancelDate"
        show-toolbar
        title="选择出生日期"
      />
    </van-popup>

    <!-- 患者详情弹窗 -->
    <van-popup
      v-model:show="showPatientDetail"
      position="bottom"
      class="patient-detail-popup"
      :style="{ height: 'auto', maxHeight: '80%', borderRadius: '16px 16px 0 0', background: '#fff' }"
      :z-index="2000"
    >
      <div class="dialog-header">
        <h3 class="dialog-title">患者详情</h3>
        <van-icon name="close" @click="showPatientDetail = false" class="close-icon" />
      </div>

      <van-cell-group class="detail-cell-group">
        <van-cell title="姓名" :value="currentPatient?.name || '未填写'" label-position="left" />
        <van-cell title="性别" :value="genderMap[currentPatient?.gender] || '未知'" label-position="left" />
        <van-cell title="年龄" :value="currentPatient?.birth_date ? `${getAge(currentPatient.birth_date)}岁` : '未填写'" label-position="left" />
        <van-cell title="出生日期" :value="currentPatient?.birth_date || '未填写'" label-position="left" />
        <van-cell title="电话号码" :value="currentPatient?.phone || '未填写'" label-position="left" />
        <van-cell title="身份证" :value="currentPatient?.id_card ||'未填写'" label-position="left" />
        <van-cell title="关系" :value="currentPatient?.relationship || '未填写'" label-position="left" />
        <van-cell title="身高" :value="currentPatient?.height ? `${currentPatient.height}cm` : '未填写'" label-position="left" />
        <van-cell title="体重" :value="currentPatient?.weight ? `${currentPatient.weight}kg` : '未填写'" label-position="left" />
        <van-cell title="血型" :value="currentPatient?.blood_type || '未填写'" label-position="left" />
      </van-cell-group>

      <div class="dialog-footer">
        <van-button block type="primary" @click="showPatientDetail = false">关闭</van-button>
      </div>
    </van-popup>

    <!-- 删除确认弹窗 -->
    <van-dialog
      v-model:show="showDeleteDialog"
      title="确认删除"
      content="确定要删除该就诊人吗？此操作不可撤销。"
      confirm-button-text="删除"
      cancel-button-text="取消"
      show-cancel-button
      confirm-button-color="#ff4d4f"
      @confirm="confirmDelete"
      @cancel="showDeleteDialog = false"
      :z-index="2000"
    />
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, onUnmounted, getCurrentInstance, nextTick ,watch} from 'vue';
import { useUserStore } from '../stores/user.js';
import { showToast } from 'vant';
import { useRouter,useRoute } from 'vue-router';


const router = useRouter();
const { proxy } = getCurrentInstance();
const userStore = useUserStore();
const route = useRoute();

// 返回上一页
const handleGoBack = () => {
  proxy?.$router ? proxy.$router.back() : window.history.back();
};


// 状态管理
const patients = ref([]); // 就诊人列表
const activePatientId = ref(null); // 当前选中患者ID
const currentPatient = ref(null); // 当前患者详情
const showPatientDetail = ref(false); // 患者详情弹窗开关
const isEditing = ref(false); // 是否编辑状态
const defaultPatientId = ref(''); // 默认就诊人ID
const showAddDialog = ref(false); // 添加/编辑弹窗开关
const showGenderPicker = ref(false); // 性别选择器开关
const showRelationPicker = ref(false); // 关系选择器开关
const showBloodTypePicker = ref(false); // 血型选择器开关
const addForm = ref(null); // 表单引用
const showDeleteDialog = ref(false); // 删除确认弹窗开关
const patientToDelete = ref(null); // 待删除患者ID
const datePickerShow = ref(false); // 日期选择器开关
const currentDate = ref([new Date().getFullYear().toString(), '01', '01']); // 当前选择的日期
const isSubmitting = ref(false); // 表单提交状态

//从浏览器获取当前登录用户信息
const userId = localStorage.getItem('userId')
const currentUserName = localStorage.getItem('username')

watch(()=>patients.value.length,(newVal,oldVal)=>{

        if(newVal!=null){
          userStore.userInfo.count=newVal;
        }

},
{immediate : true}
)




// 新患者数据
const newPatient = reactive({
  patient_id: '',
  name: '',
  gender: '',
  genderText: '',
  birthDate: '',
  phone: '',
  idCard: '',
  relationship: '',
  relationText: '',
  height: '',
  weight: '',
  blood_type: '',
  bloodTypeText: '',
  birth_date: ''
});

// 选项数据
const genderOptions = [
  { text: '男', value: '男' },
  { text: '女', value: '女' },
  { text: '未知', value: '未知' }
];
const relationOptions = [
  { text: '本人', value: '本人' },
  { text: '配偶', value: '配偶' },
  { text: '父亲', value: '父亲' },
  { text: '母亲', value: '母亲' },
  { text: '儿子', value: '儿子' },
  { text: '女儿', value: '女儿' },
  { text: '其他亲属', value: '其他亲属' },
  { text: '朋友', value: '朋友' }
];
const bloodTypeOptions = [
  { text: 'A型', value: 'A型' },
  { text: 'B型', value: 'B型' },
  { text: 'AB型', value: 'AB型' },
  { text: 'O型', value: 'O型' },
  { text: '未知', value: '未知' }
];

// 性别映射（兼容后端数据）
const genderMap = ref({
  0: '未知',
  1: '男',
  2: '女',
  未知: 0,
  男: 1,
  女: 2
});

// 滑动单元格状态
const openedSwipeId = ref(''); // 当前打开的滑动单元格ID

const handleOpenGenderPicker = () => {
  showGenderPicker.value = true;
};

const handleOpenRelationPicker = () => {
  showRelationPicker.value = true;
};

const handleOpenBloodTypePicker = () => {
  showBloodTypePicker.value = true;
};

// 日期选择器逻辑
const monthOptions = computed(() => {
  const options = [];
  for (let i = 1; i <= 12; i++) {
    options.push({ text: `${i}月`, value: i.toString().padStart(2, '0') });
  }
  return options;
});
const isLeapYear = (year) => (year % 4 === 0 && year % 100 !== 0) || (year % 400 === 0);
const getDaysInMonth = (year, month) => {
  const daysInMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
  return month === 2 && isLeapYear(year) ? 29 : daysInMonth[month - 1];
};
const dayOptions = computed(() => {
  const year = parseInt(currentDate.value[0]) || new Date().getFullYear();
  const month = parseInt(currentDate.value[1]) || 1;
  const days = getDaysInMonth(year, month);
  return Array.from({ length: days }, (_, i) => ({
    text: `${i + 1}日`,
    value: (i + 1).toString().padStart(2, '0')
  }));
});
const yearOptions = computed(() => {
  const currentYear = new Date().getFullYear();
  return Array.from({ length: 100 }, (_, i) => ({
    text: `${currentYear - i}年`,
    value: (currentYear - i).toString()
  }));
});
const dateColumns = computed(() => [yearOptions.value, monthOptions.value, dayOptions.value]);

const onDateChange = (event) => {
  const [year, month, day] = event.selectedValues;
  const daysInMonth = getDaysInMonth(+year, +month);
  if (+day > daysInMonth) {
    currentDate.value = [year, month, daysInMonth.toString().padStart(2, '0')];
  } else {
    currentDate.value = [year, month, day];
  }
};
const showDatePopup = () => (datePickerShow.value = true);
const confirmDate = (event) => {
  const [year, month, day] = event.selectedValues;
  newPatient.birthDate = `${year}-${month}-${day}`;
  newPatient.birth_date = newPatient.birthDate;
  datePickerShow.value = false;
};
const cancelDate = () => (datePickerShow.value = false);

// 表单提交
const submitForm = () => {
  if (addForm.value) {
    isSubmitting.value = true;
    addForm.value.submit();
  }
};

// 滑动单元格事件
const handleSwipeOpen = (id) => (openedSwipeId.value = id);
const handleSwipeClose = () => (openedSwipeId.value = '');

// 患者详情
const setActivePatient = (id) => {
  if (openedSwipeId.value) return (openedSwipeId.value = '');
  activePatientId.value = id;
  currentPatient.value = patients.value.find((p) => p.patient_id === id);
  showPatientDetail.value = !!currentPatient.value;
};

// 默认就诊人切换
const toggleDefaultPatient = (id) => {
  if (openedSwipeId.value) return (openedSwipeId.value = '');
  if (defaultPatientId.value === id) {
    defaultPatientId.value = '';
    showToast(`已取消默认就诊人`);
  } else {
    defaultPatientId.value = id;
    proxy.$axios.put('/api/v1/patient/default', {
      user_id: userStore.userInfo.user_id,
      patient_id: id
    }).then(()=>{proxy.$axios.get("/api/v1/patient/getDefault",{params:{user_id:userStore.userInfo.user_id}})
        .then((serverData)=>{
          if(serverData.data.code==0){
            userStore.defaultPatient=serverData.data.data;
          }
        })})
    showToast(`已设置为默认就诊人`);
  }
};

// 编辑患者
const editPatient = (id) => {
  if (openedSwipeId.value) return (openedSwipeId.value = '');
  const patient = patients.value.find((p) => p.patient_id === id);
  if (!patient) return showToast('患者不存在');
  isEditing.value = true;
  newPatient.patient_id = id;
  newPatient.name = patient.name;
  newPatient.gender = genderMap.value[patient.gender] || patient.gender;
  newPatient.genderText = genderOptions.find((item) => item.value === newPatient.gender)?.text || '';
  newPatient.birthDate = patient.birth_date || '';
  newPatient.birth_date = patient.birth_date || '';
  if (patient.birth_date) {
    const [year, month, day] = patient.birth_date.split('-');
    currentDate.value = [year, month, day];
  }
  newPatient.phone = patient.phone;
  newPatient.idCard = patient.id_card || '';
  newPatient.relationship = patient.relationship;
  newPatient.relationText = relationOptions.find((item) => item.value === patient.relationship)?.text || '';
  newPatient.height = patient.height || '';
  newPatient.weight = patient.weight || '';
  newPatient.blood_type = patient.blood_type || '';
  newPatient.bloodTypeText = patient.blood_type || '';
  showAddDialog.value = true;
};

// 删除患者
const deletePatient = (id) => {
  if (defaultPatientId.value === id) defaultPatientId.value = '';
  patientToDelete.value = id;
  showDeleteDialog.value = true;
};
const confirmDelete = () => {
  if (!patientToDelete.value) return;
  patients.value = patients.value.filter((p) => p.patient_id !== patientToDelete.value);
  proxy.$axios.delete(`/api/v1/patient/${patientToDelete.value}`);
  showToast('删除成功');
  showDeleteDialog.value = false;
  patientToDelete.value = null;
  openedSwipeId.value = '';
};

// 添加就诊人弹窗
const showAddPatientDialog = () => {
  resetForm();
  isEditing.value = false;
  showAddDialog.value = true;
};
const resetForm = () => {
  newPatient.patient_id = '';
  newPatient.name = '';
  newPatient.gender = '';
  newPatient.genderText = '';
  newPatient.birthDate = '';
  newPatient.birth_date = '';
  newPatient.phone = '';
  newPatient.idCard = '';
  newPatient.relationship = '';
  newPatient.relationText = '';
  newPatient.height = '';
  newPatient.weight = '';
  newPatient.blood_type = '';
  newPatient.bloodTypeText = '';
  currentDate.value = [new Date().getFullYear().toString(), '01', '01'];
  addForm.value?.resetValidation();
  showAddDialog.value = false;
  isSubmitting.value = false;
};

// 表单提交逻辑
const handleAddConfirm = async () => {
  try {
    if (!addForm.value) throw new Error('表单未找到');
    await addForm.value.validate();
    const encryptedIdCard = newPatient.idCard.replace(/^(\d{6})\d+(\d{4})$/, '$1********$2'); // 掩码处理

    const patientData = {
      name: newPatient.name,
      gender: newPatient.gender,
      birth_date: newPatient.birthDate,
      phone: newPatient.phone,
      id_card: newPatient.idCard,
      relationship: newPatient.relationship,
      height: newPatient.height,
      weight: newPatient.weight,
      blood_type: newPatient.blood_type
    };

    if (newPatient.patient_id) {
      // 编辑逻辑
      const index = patients.value.findIndex((p) => p.patient_id === newPatient.patient_id);
      if (index !== -1) {
        patients.value[index] = { ...patients.value[index], ...patientData };
        proxy.$axios.put('/api/v1/patient', {
          ...patientData,
          patient_id: newPatient.patient_id,
          gender: genderMap.value[newPatient.gender]
        }).then((res) => {
          if (res.data.code === 0) {
            showToast('修改成功');
            initData();
          } else {
            console.log(res.data.message);
            showToast('修改失败');
          }
        });
      }
    } else {
      // 新增逻辑
      const newId = `P${Date.now()}`;
      patients.value.push({ ...patientData, patient_id: newId, is_default: patients.value.length === 0 ? 1 : 0 });
      proxy.$axios.post('/api/v1/patient', {
        ...patientData,
        user_id: userStore.userInfo.user_id,
        gender: genderMap.value[newPatient.gender]
      }).then((res) => {
        if (res.data.code === 0) {
          showToast('添加成功');
          initData();
          if (patients.value.length === 1) defaultPatientId.value = newId;
        } else {
          showToast('添加失败');
        }
      });
    }

    showAddDialog.value = false;
    isSubmitting.value = false;
  } catch (error) {
    isSubmitting.value = false;
    showToast('表单填写有误，请检查');
  }
};

// 选择器确认事件
const onGenderConfirm = (valueObj) => {
  const value = valueObj.selectedValues[0];
  const item = genderOptions.find((item) => item.value === value);
  if (item) {
    newPatient.gender = item.value;
    newPatient.genderText = item.text;
  }
  showGenderPicker.value = false;
  nextTick(() => addForm.value?.validateField('genderText'));
  // nextTick(() => addForm.value?.validate('genderText')); // 修复：使用 validate 方法并传入字段名
};
const onRelationConfirm = (valueObj) => {
  const value = valueObj.selectedValues[0];
  const item = relationOptions.find((item) => item.value === value);
  if (item) {
    newPatient.relationship = item.value;
    newPatient.relationText = item.text;
  }
  showRelationPicker.value = false;
  nextTick(() => addForm.value?.validateField('relationText'));
  // nextTick(() => addForm.value?.validate('relationText')); // 修复：使用 validate 方法并传入字段名

};
const onBloodTypeConfirm = (valueObj) => {
  const value = valueObj.selectedValues[0];
  const item = bloodTypeOptions.find((item) => item.value === value);
  if (item) {
    newPatient.blood_type = item.value;
    newPatient.bloodTypeText = item.text;
  }
  showBloodTypePicker.value = false;
  nextTick(() => addForm.value?.validateField('bloodTypeText'));
  // nextTick(() => addForm.value?.validate('bloodTypeText')); // 修复：使用 validate 方法并传入字段名

};

// 年龄计算
const getAge = (birth_date) => {
  if (!birth_date) return 0;
  const birth = new Date(birth_date);
  const now = new Date();
  let age = now.getFullYear() - birth.getFullYear();
  if (now.getMonth() < birth.getMonth() || (now.getMonth() === birth.getMonth() && now.getDate() < birth.getDate())) {
    age--;
  }
  return age;
};

// 身份证掩码
const maskIdCard = (idCard) => {
  if (!idCard || idCard.length !== 18) return idCard;
  return idCard.replace(/^(\d{6})\d+(\d{4})$/, '$1********$2');
};

// 初始化数据
const initData = () => {
  proxy.$axios.get('/api/v1/patient', {
    params: { user_id: userStore.userInfo.user_id }
  }).then((res) => {
    if (res.data.code == 0) {
      patients.value = res.data.data;
      if (patients.value.length) {
        const defaultPatient = patients.value.find((p) => p.is_default === 1);
        defaultPatientId.value = defaultPatient?.patient_id || patients.value[0].patient_id;
      }
    }
  });
};

// 检查是否有传入的 patientId 并显示详情
const checkAndShowPatientDetail = () => {
  // 从路由查询参数中获取 patientId
  const patientId = route.query.patientId
  if (patientId) {
    // 查找匹配的患者
    const patient = patients.value.find(p => p.patient_id == patientId)
    if (patient) {
      // 设置当前患者并显示详情弹窗

      currentPatient.value = patient
      activePatientId.value = patientId
      showPatientDetail.value = true
    }
  }
}

// 底部间距自适应
const adjustContentPadding = () => {
  nextTick(() => {
    const footer = document.querySelector('.add-patient-btn');
    const content = document.querySelector('.patient-cards-container');
    if (footer && content) {
      content.style.paddingBottom = `${footer.offsetHeight + 20}px`;
    }
  });
};

onMounted(() => {
  initData();
  adjustContentPadding();
  window.addEventListener('resize', adjustContentPadding);
});

onUnmounted(() => {
  window.removeEventListener('resize', adjustContentPadding);
});
</script>

<style scoped>
.patient-management {
  display: flex;
  flex-direction: column;
  background-color: #f5f7fa;
  min-height: 100vh;
  position: relative;
}

/* 导航栏 */
.van-nav-bar {
  background-color: #1989fa;
  color: white;
  z-index: 101 !important;
}
.van-nav-bar__title,
.van-nav-bar__left {
  color: white !important;
}

/* 患者卡片容器 */
.patient-cards-container {
  padding: 12px 0;
  flex: 1;
  overflow-y: auto;
  -webkit-overflow-scrolling: touch;
}
.empty-tip {
  text-align: center;
  padding: 40px 0;
  color: #999;
  font-size: 14px;
}

/* 滑动单元格 */
.patient-swipe-cell {
  margin: 4px 16px;
  border-radius: 10px;
  overflow: hidden;
}

/* 患者卡片 */
.patient-card {
  background: white;
  border-radius: 10px;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.05);
  padding: 8px 12px;
  transition: transform 0.2s, box-shadow 0.2s;
}
.patient-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
}
.patient-card.active-patient {
  border: 2px solid #1989fa;
}

.patient-header {
  display: flex;
  position: relative;
}
.default-star {
  position: absolute;
  top: 8px;
  right: 8px;
  font-size: 18px;
  cursor: pointer;
  transition: all 0.2s ease;
  z-index: 10;
}
.default-star:hover {
  transform: scale(1.1);
}
.filled-star {
  stroke: none !important;
}

.patient-info {
  flex: 1;
}
.name-and-tag {
  display: flex;
  align-items: center;
  margin-bottom: 6px;
}
.patient-name {
  font-size: 14px;
  font-weight: bold;
  color: #333;
  margin-right: 8px;
}
.relation-tag {
  margin-top: 2px;
  font-size: 12px;
}

.patient-details {
  display: flex;
  flex-direction: column;
  gap: 4px;
}
.detail-item {
  display: flex;
  align-items: center;
  font-size: 12px;
  color: #555;
}
.detail-item .van-icon {
  margin-right: 5px;
  color: #1989fa;
  font-size: 13px;
}

.card-footer {
  padding: 8px 0 0 0;
  border-top: 1px solid #f5f5f5;
  display: flex;
  justify-content: flex-end;
  margin-top: 4px;
}
.edit-btn {
  padding: 0 12px;
  height: 24px;
  font-size: 11px;
  margin-left: 8px;
}

.delete-button {
  height: 100%;
  width: 60px;
  border-radius: 0;
  font-size: 13px;
  display: flex;
  align-items: center;
  justify-content: center;
}

/* 添加按钮 */
.add-patient-btn {
  position: fixed;
  bottom: 30px;
  left: 50%;
  transform: translateX(-50%);
  width: calc(100% - 60px);
  max-width: 300px;
  height: 46px;
  background: linear-gradient(135deg, #1989fa, #3a8df8);
  border: none;
  color: white;
  font-weight: bold;
  font-size: 16px;
  box-shadow: 0 6px 12px rgba(25, 137, 250, 0.3);
  z-index: 1000;
}
.add-patient-btn .van-icon {
  margin-right: 6px;
}

/* 弹窗样式 */
.patient-detail-popup {
  padding: 24px;
  box-sizing: border-box;
  width: 100%;
}
.dialog-header {
  margin-bottom: 20px;
  text-align: center;
  position: relative;
}
.close-icon {
  position: absolute;
  right: 12px;
  top: 8px;
  color: #999;
  font-size: 20px;
}
.dialog-title {
  font-size: 18px;
  font-weight: bold;
  color: #333;
}
.detail-cell-group {
  margin-bottom: 24px;
}
.detail-cell-group .van-cell {
  background: transparent;
  padding: 12px 16px;
  border-bottom: 1px solid #f5f5f5;
}
.detail-cell-group .van-cell:last-child {
  border-bottom: none;
}
.detail-cell-group .van-cell__title {
  color: #666;
}
.detail-cell-group .van-cell__value {
  color: #333;
}
.dialog-footer {
  padding-top: 16px;
}
.dialog-footer .van-button {
  height: 44px;
  line-height: 44px;
  border-radius: 8px;
  background: linear-gradient(135deg, #1989fa, #3a8df8);
  border: none;
  color: white;
  font-weight: bold;
}

/* 表单 */
.scrollable-form {
  max-height: 70vh;
  overflow-y: auto;
  padding-bottom: 16px;
}
.van-field__error-message {
  color: #f56c6c;
}
.dialog-footer-buttons {
  display: flex;
  justify-content: space-between;
  padding: 10px 16px;
  gap: 10px;
}
.dialog-btn {
  flex: 1;
  height: 44px;
  line-height: 44px;
  border-radius: 8px;
}
.cancel-btn {
  background-color: #f5f5f5;
  color: #333;
}
.confirm-btn {
  background: linear-gradient(135deg, #1989fa, #3a8df8);
  color: #fff;
}
.required-asterisk {
  color: #f53f3f;
  margin-left: 3px;
  font-size: 14px;
}
.required-field {
  --van-field-label-color: #333;
}
.required-field .van-field__label {
  font-weight: 500;
}
.optional-field {
  --van-field-label-color: #666;
}
.optional-field .van-field__input::placeholder {
  color: #999;
  font-size: 13px;
}
.van-field {
  margin-bottom: 8px;
}
.required-field + .optional-field {
  margin-top: 4px;
}

/* 选择器 */
.van-picker {
  width: 100%;
}
.van-field__control--readonly {
  color: #323233;
}

/* 弹窗层级 */
.van-popup, .van-dialog {
  z-index: 2000 !important;
}
</style>